<?php

namespace app\common\model;

use app\common\model\order\Goods;
use think\Log;
use think\Model;

/**
 * 会员余额日志模型
 */
class MoneyLog extends Model
{

    // 表名
    protected $name = 'user_money_log';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = '';
    // 追加属性
    protected $append = [
        'createtime_text'
    ];
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function userinfo()
    {
        return $this->belongsTo(User::class, 'uid', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    /**
     * @author LK
     * @date: 2023-10-23 
     * @param object $order  待结算佣金明细
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    static function frozenlog_commission($order)
    {

        $user = User::get($order->user_id);

        if (!$user) {
            return true;
        }
        bcscale(2);
        $pUser = User::get($user->pid);
        if (!$pUser) {
            $pUser = User::get(1);
        }
        if ($pUser) {
            //非创业专区直推收益
            if ($order['type'] == '1') {
                $b_direct = Goods::where('order_id', $order->id)->sum('b_direct');
                Frozenlog::money($b_direct, $user->pid, '直推收益(非创业专区)', $order->id, 0);
            }
            //创业专区
            if ($order['type'] == '2') {
                $goods =  Goods::where('order_id', $order->id)->select();
                $groupList =  UserGroup::getGroupList();
                foreach ($goods as $k => $v) {

                    if ($order['meal'] == '0') {
                        $parallel_grade = 0;
                        //创业专区级差收益(零售)
                        $money = $v[$groupList[$user->group_id]];
                        $pid = $user->pid;
                        //创业专区直推平级收益(零售)
                        if ($v->parallel_grade > 0) {
                            if ($user->group_id == 1 && $user->group_id > $pUser->group_id) {
                                User::money($v->parallel_grade, $user->pid, '直推收益(零售)', $order->id, $v->id);
                            } elseif ($user->group_id == $pUser->group_id) {
                                User::money($v->parallel_grade, $user->pid, '平级收益(零售)', $order->id, $v->id);
                                $parallel_grade = $v->parallel_grade;
                            } else {
                                $puser = User::get($user->pid);
                                $acourmt = bcsub($money, $v[$groupList[$puser->group_id]], 2);
                                if ($acourmt > 0) {
                                    User::money($acourmt, $user->pid, '代理级差收益(零售)', $v->order_id, $v->id);
                                    $money = bcsub($money, $acourmt, 2);
                                    $pid = $puser->pid;
                                }
                            }
                        }
                        //极差需减去平级奖励
                        $money = bcsub($money, $parallel_grade, 2);
                        if ($money > 0) {
                            self::digui($v, $user->group_id, $pid, $money);
                        }
                    } else {

                        //创业专区直推收益(套餐)
                        if ($v->direct > 0) {
                            $point = bcmul($v->direct, 0.2, 2);
                            $yue = bcmul($v->direct, 0.7, 2);

                            User::money($yue, $pUser->id, '直推收益(套餐)', $order->id, $v->id);
                            User::score($point, $pUser->id, '直推收益(套餐)', $order->id, $v->id);

                            if ($pUser->id != 1) {
                                self::assist_award($v->direct, $pUser->id, $v);
                            }
                        }
                        //平级奖
                        // if ($user->group_id > 1 && $v->parallel_grade > 0) {
                        //     $parent_ids = $user['parent_ids'];
                        //     $flat = User::where('group_id', $user->group_id)->whereIn('id', $parent_ids)->orderRaw("field(id,$parent_ids)")->find();
                        //     if ($flat) {
                        //         $point = bcmul($v->parallel_grade, 0.2, 0);
                        //         $yue = bcmul($v->parallel_grade, 0.7, 2);
                        //         User::money($yue, $flat->id, '平级收益(套餐)', $order->id, $v->id);
                        //         User::score($point, $flat->pid, '平级收益(套餐)', $order->id, $v->id);
                        //         self::assist_award($v->parallel_grade, $user->pid, $v);
                        //     }
                        // }
                        //团队奖

                        self::team_digui($v, $pUser->id);
                        //伯乐奖
                        if ($v->direct > 0) {
                            self::talent_scout_digui($v, $pUser->pid, $v->direct);
                        }
                        //营业额加权分红
                        // $uids = User::where('group_id', 10)->column('id');
                        // if ($uids && $v->dividend > 0) {
                        //     foreach ($uids as $k => $v) {
                        //         User::money($v->dividend, $v, '加权分红(套餐)', $v->order_id, $v->id);
                        //     }
                        // }
                    }
                }
            }
        }
        return true;
    }

    //递归创业专区级差收益(零售)
    static function digui($ordergoods, $group_id, $pid, $money = 0)
    {
        $groupList =  UserGroup::getGroupList();
        $puser = User::get($pid);
        if (!$puser) {
            return;
        }
        if ($group_id < $puser->group_id) {
            $acourmt = bcsub($money, $ordergoods[$groupList[$puser->group_id]], 2);

            if ($acourmt > 0) {
                User::money($acourmt, $pid, '代理级差收益(零售)', $ordergoods->order_id, $ordergoods->id);
                if ($puser->pid > 0) {
                    $after = bcsub($money, $acourmt, 2);
                    if ($after > 0) {
                        self::digui($ordergoods, $puser->group_id, $puser->pid, $after);
                    }
                }
            }
        } else {
            if ($money > 0) {
                self::digui($ordergoods, $puser->group_id, $puser->pid, $money);
            }
        }
    }
    //创业专区平级奖收益(套餐)
    static function parallel_award($money, $pid, $ordergoods, $group_id = 0)
    {

        $user = User::get($pid);
        if (!$user) {
            return true;
        }
        if (!$user['parent_ids']) {
            return true;
        }
        $parent_ids = $user['parent_ids'];
        $flat = User::where('group_id', $group_id)->whereIn('id', $parent_ids)->orderRaw("field(id,$parent_ids)")->find();
        if ($flat) {
            $money = $money * 0.1;

            $point = bcmul($money, 0.2, 2);
            $yue = bcmul($money, 0.7, 2);
            User::money($yue, $flat->id, '平级收益(套餐)', $ordergoods->order_id, $ordergoods->id);
            User::score($point, $flat->id, '平级收益(套餐)',  $ordergoods->order_id, $ordergoods->id);
            if ($flat->id != 1) {
                self::assist_award($money, $flat->id, $ordergoods);
            }
            return true;
        }
        return false;
    }
    //创业专区互助奖收益(套餐)
    static function assist_award($yue, $pid, $ordergoods)
    {

        $mutual = bcmul($yue, 0.1, 2);
        $uids = User::where('pid', $pid)->where('group_id', '>', 1)->column('id');
        $ids = User::where('pid', $pid)->column('id');
        $userids = array_merge($uids, User::whereIn('pid', $ids)->where('group_id', '>', 1)->column('id'));
        if ($mutual > 0 && count($userids) > 0) {
            $hzj = bcdiv($mutual, count($userids), 2);
            if ($hzj > 0) {
                foreach ($userids as $k => $v) {
                    User::money($hzj, $v, '互助收益(套餐)', $ordergoods->order_id, $ordergoods->id);
                }
            }
        }
    }
    //创业专区伯乐奖收益(套餐)
    static function talent_scout_digui($ordergoods, $pid, $money = 0)
    {

        $puser = User::get($pid);
        if (!$puser) {
            return;
        }
        if ($puser['group_id'] <= 1) {
            return;
        }
        $group = UserGroup::get($puser['group_id']);
        $scale = $group['talent_scout'];
        $talent_scout = $scale / 100;
        $money = bcmul($money, $talent_scout, 2);
        if ($money > 0) {
            $point = bcmul($money, 0.2, 2);
            $yue = bcmul($money, 0.7, 2);

            User::money($yue, $pid, '伯乐奖收益(套餐)', $ordergoods->order_id, $ordergoods->id);
            User::score($point, $pid, '伯乐奖收益(套餐)', $ordergoods->order_id, $ordergoods->id);
            if ($pid != 1) {
                self::assist_award($money, $pid, $ordergoods);
            }
            if ($puser['pid'] > 0) {
                self::talent_scout_digui($ordergoods, $puser['pid'], $money);
            }
        }
    }
    //创业专区团队奖收益(套餐)
    static function team_digui($ordergoods, $pid,  $group_id = 0, $scalee = 0, $check = false)
    {

        $puser = User::get($pid);
        if (!$puser) {
            return;
        }
   
        if ($puser['group_id'] <= 2) {
            if ($puser['pid'] <= 0) {
                return;
            }
            self::team_digui($ordergoods,  $puser['pid'], $group_id, $scalee, false);
        } else {
            $group = UserGroup::get($puser['group_id']);
            $scale = $group['new_team_performance'] - $scalee;
            if ($puser['group_id'] > $group_id) {
                $new_team_performance = $scale / 100;
                $money = bcmul($ordergoods['pay_fee'], $new_team_performance, 2);
                if ($money > 0) {
                    $point = bcmul($money, 0.2, 2);
                    $yue = bcmul($money, 0.7, 2);
                    User::money($yue, $pid, '团队奖收益(套餐)', $ordergoods->order_id, $ordergoods->id);

                    User::score($point, $pid, '团队奖收益(套餐)', $ordergoods->order_id, $ordergoods->id);
                    if ($check == false) {
                        $check = self::parallel_award($money, $pid, $ordergoods, $puser['group_id']);
                    }
                    if ($pid != 1) {
                        self::assist_award($money, $pid, $ordergoods);
                        self::team_digui($ordergoods, $puser['pid'], $puser['group_id'], $group['new_team_performance'], $check);
                    }
                }
            } else {
                self::team_digui($ordergoods,  $puser['pid'], $group_id, $scalee, false);
            }
        }
    }







    /**
     * @author LK
     * @date: 2023-10-23 
     * @param array $order  订单分佣
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    static function commission($orders)
    {
        try {
            foreach ($orders as $k => $v) {
                $acourmt = Frozenlog::all(['order_id' => $v['id'], 'memo' => '代理级差收益(零售)']);
                if ($acourmt) {
                    foreach ($acourmt as  $vv) {
                        User::money($vv->money, $vv->user_id, '代理级差收益(零售)', $vv->order_id, $vv->o_g_id);
                        $vv->is_settle = 1;
                        $vv->save();
                    }
                }
                $parallel_grade = Frozenlog::all(['order_id' => $v['id'], 'memo' => '平级收益(零售)']);
                if ($parallel_grade) {
                    foreach ($parallel_grade as $k => $vv) {
                        User::money($vv->money, $vv->user_id, '平级收益(零售)', $vv->order_id, $vv->o_g_id);
                        $vv->is_settle = 1;
                        $vv->save();
                    }
                }
                $direct = Frozenlog::all(['order_id' => $v['id'], 'memo' => '直推收益(零售)']);
                if ($direct) {
                    foreach ($direct as $k => $vv) {
                        User::money($vv->money, $vv->user_id, '直推收益(零售)', $vv->order_id, $vv->o_g_id);
                        $vv->is_settle = 1;
                        $vv->save();
                    }
                }
                $b_direct = Frozenlog::all(['order_id' => $v['id'], 'memo' => '直推收益(非创业专区)']);
                if ($b_direct) {
                    foreach ($b_direct as $k => $vv) {
                        User::money($vv->money, $vv->user_id, '直推收益(非创业专区)', $vv->order_id, $vv->o_g_id);
                        $vv->is_settle = 1;
                        $vv->save();
                    }
                }

                $v->is_settle = 1;
                $v->save();
            }
        } catch (\Exception $e) {
            exception($e->getMessage());
        }
        return true;
    }
}
